// Read_NTAGDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Read_NTAG.h"
#include "Read_NTAGDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

#include "umfh.h"
#pragma comment(lib,"umf.lib")

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CRead_NTAGDlg dialog

CRead_NTAGDlg::CRead_NTAGDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CRead_NTAGDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CRead_NTAGDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CRead_NTAGDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CRead_NTAGDlg)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CRead_NTAGDlg, CDialog)
	//{{AFX_MSG_MAP(CRead_NTAGDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BTN_LINK, OnBtnLink)
	ON_BN_CLICKED(IDC_BTN_READ, OnBtnRead)
	ON_BN_CLICKED(IDC_BTN_READ_S, OnBtnReadS)
	ON_BN_CLICKED(IDC_BTN_WRITE_S, OnBtnWriteS)
	ON_BN_CLICKED(IDC_BTN_AUTHEN, OnBtnAuthen)
	ON_BN_CLICKED(IDC_BTN_FINDCARD, OnBtnFindcard)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CRead_NTAGDlg message handlers

void CRead_NTAGDlg::RemapCtrl()
{
	m_btn_link = (CButton*)GetDlgItem(IDC_BTN_LINK);
	m_edt_data = (CEdit*)GetDlgItem(IDC_EDIT_DATA);
	m_stc_msg = (CStatic*)GetDlgItem(IDC_STATIC_MSG);
	m_combo_port = (CComboBox*)GetDlgItem(IDC_COMBO_PORT);
	m_combo_baud = (CComboBox*)GetDlgItem(IDC_COMBO_BAUD);
	m_edit_blkTest_blk = (CEdit*)GetDlgItem(IDC_EDIT_BLK);
	m_edit_blkTest_blkData = (CEdit*)GetDlgItem(IDC_EDIT_SDATA);
	m_edit_blkTest_pwd = (CEdit*)GetDlgItem(IDC_EDIT_PWD);
}

BOOL CRead_NTAGDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	RemapCtrl();
	m_combo_port->SetCurSel(0);
	m_combo_baud->SetCurSel(0);
	m_edit_blkTest_blk->SetWindowText("4");
	m_edit_blkTest_blkData->SetWindowText("11223344");
	m_edit_blkTest_pwd->SetWindowText("FFFFFFFF");

	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CRead_NTAGDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CRead_NTAGDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CRead_NTAGDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}


int gl_icdev = -1;
CString gl_msg;

int CRead_NTAGDlg::GetCurrentPort()
{
	int iCurSel = m_combo_port->GetCurSel();
	switch(iCurSel)
	{
	case 0:
		return 100;
	default:
		return iCurSel -1;
	}
}

int CRead_NTAGDlg::GetCurrentBaud()
{
	int iCurSel = m_combo_baud->GetCurSel();
	CString strText;
	int baud;

	m_combo_baud->GetLBText(iCurSel,strText);

	baud = _ttoi(strText);

	return baud;

}

void CRead_NTAGDlg::OnBtnLink() 
{
	// TODO: Add your control notification handler code here
	if(gl_icdev == -1)
	{
		gl_icdev = fw_init(GetCurrentPort(), GetCurrentBaud());

		if(gl_icdev != -1)
		{
			MessageBox("Link ok", "Success", MB_OK|MB_ICONINFORMATION);
			m_btn_link->SetWindowText("UnLink");
		}
		else
		{
			MessageBox("Link failed", "Error", MB_OK|MB_ICONERROR);
		}
		
	}
	else
	{
		fw_exit(gl_icdev);
		gl_icdev = -1;
		m_btn_link->SetWindowText("Link");
	}
}

BOOL CRead_NTAGDlg::CheckPortOpenStatus()
{
	if(gl_icdev == -1)
	{
		MessageBox("Device is not linke","Warnning", MB_OK|MB_ICONWARNING);
		return FALSE;
	}
	else
		return TRUE;
}

void CRead_NTAGDlg::ShowMsg(CString str)
{
	m_stc_msg->SetWindowText(str);
}

void CRead_NTAGDlg::AddItemData(CString str)
{
	gl_msg += str;

	m_edt_data->SetWindowText(gl_msg);
}

void CRead_NTAGDlg::ClearData()
{
	gl_msg = "";
}

int CRead_NTAGDlg::ReadTag()
{
	int st = 0;
	unsigned long snr;
	int curPage = 0;
	unsigned char rData[128] ={0};
	unsigned char szData[128]={0};
	CString strItemData;

	if(FALSE == FindCard())
		goto DEXIT;

	ShowMsg("Find Card, Reading...");

	ClearData();

	while(st == 0)
	{
		st = fw_read_ultralt(gl_icdev, curPage, rData);
		if(0 ==st)
		{
			hex_a(szData, rData, 8);
			strItemData.Format("Page[%d]:\t\t%s\r\n", curPage,szData);
			AddItemData(strItemData);
			curPage++;
		}
	}

	ShowMsg("Read Over");

DEXIT:
	return st;
}

void CRead_NTAGDlg::OnBtnRead() 
{
	// TODO: Add your control notification handler code here
	if(FALSE == CheckPortOpenStatus())
	{
		return;
	}

	ReadTag();
}

BOOL CRead_NTAGDlg::GetTagPwdParam(unsigned char* pData)
{
	CString strPwd;
	int str_len;
	unsigned char szPwd[16];

	m_edit_blkTest_pwd->GetWindowText(strPwd);

	str_len = strPwd.GetLength();
	if(str_len != 8)
	{
		ShowMsg("Password invalid length (need 8 chars)");
		return FALSE;
	}
	
	strcpy((char*)szPwd, strPwd.GetBuffer(str_len));
	if(a_hex(pData, szPwd, str_len/2))
	{
		ShowMsg("Password format (need hex format string)");
		return FALSE;
	}

	return TRUE;

}

BOOL CRead_NTAGDlg::GetBlockTestParam(int* pBlk, unsigned char* pData)
{
	CString strData;
	int str_len;
	unsigned char szData[16];

	*pBlk = GetDlgItemInt(IDC_EDIT_BLK);
	m_edit_blkTest_blkData->GetWindowText(strData);

	str_len = strData.GetLength();
	if(str_len != 8)
	{
		ShowMsg("Data for r/w invalid length (need 8 chars)");
		return FALSE;
	}
	
	strcpy((char*)szData, strData.GetBuffer(str_len));
	if(a_hex(pData, szData, str_len/2))
	{
		ShowMsg("Data for r/w invalid format (need hex format string)");
		return FALSE;
	}

	return TRUE;

}


BOOL CRead_NTAGDlg::FindCard()
{

	BOOL st = FALSE;
	int opst;
	unsigned long snr;
	CString strItemData;

	if(FALSE == CheckPortOpenStatus())
	{
		goto DEXIT;
	}

	opst = fw_card(gl_icdev, 1, &snr);
	if(opst)
	{
		ShowMsg("Find NO Tag");

		goto DEXIT;
	}

	opst = fw_anticoll2(gl_icdev, 0, &snr);
	if(opst)goto DEXIT;

	opst= fw_select2(gl_icdev, snr);
	if(opst) goto DEXIT;

	ShowMsg("Find Tag");

	st = TRUE;

DEXIT:
	return st;
}

void CRead_NTAGDlg::OnBtnReadS() 
{
	// TODO: Add your control notification handler code here
	int st;
	int curPage = GetDlgItemInt(IDC_EDIT_BLK);
	unsigned char rData[128] ={0};
	unsigned char szData[128]={0};
	CString strItemData;

	if(FALSE == CheckPortOpenStatus())
	{
		return;
	}

	st = fw_read_ultralt(gl_icdev, curPage, rData);
	if(0 ==st)
	{
		hex_a(szData, rData, 8);
		m_edit_blkTest_blkData->SetWindowText((CString)szData);
		ShowMsg("Read ok");
	}
	else 
		ShowMsg("Read failed");

DEXIT:
	return;
}

void CRead_NTAGDlg::OnBtnWriteS() 
{
	// TODO: Add your control notification handler code here
	int curPage;
	int st;
	unsigned char bufData[12];

	if(FALSE == CheckPortOpenStatus())
		return;

	if(FALSE == GetBlockTestParam(&curPage, bufData))
		return;

	st = fw_write_ultralt(gl_icdev, curPage, bufData);
	if(0 ==st)
	{
		ShowMsg("Write ok");
	}
	else 
		ShowMsg("Write failed");

DEXIT:
	return;

}

void CRead_NTAGDlg::OnBtnAuthen() 
{
	// TODO: Add your control notification handler code here
	int st;
	unsigned char bufPwd[12];

	if(FALSE == CheckPortOpenStatus())
		return;

	if(FALSE == GetTagPwdParam( bufPwd))
		return;

	st = fw_tag_authenPwd(gl_icdev, bufPwd);
	if(0 ==st)
	{
		ShowMsg("Authen ok");
	}
	else 
		ShowMsg("Authen failed");

DEXIT:
	return;
}

void CRead_NTAGDlg::OnBtnFindcard() 
{
	// TODO: Add your control notification handler code here
	FindCard();
}
